using Newtonsoft.Json;

namespace ShopForWeb.UI.Extensions;

/// <summary>
/// Session的扩展方法包
/// </summary>
public static class SessionExtension
{
  /// <summary>
  /// object转Json字符串，存Session
  /// </summary>
  /// <param name="session">扩展Session</param>
  /// <param name="key">key</param>
  /// <param name="value">object</param>
  /// <typeparam name="T">object的类型，泛型写法</typeparam>
  public static void Set<T>(this ISession session, string key, T value)
  {
    session.SetString(key, JsonConvert.SerializeObject(value));
  }

  /// <summary>
  /// Session存的Json字符串传指定类型的object
  /// </summary>
  /// <param name="session">扩展Session</param>
  /// <param name="key">key</param>
  /// <typeparam name="T">object的类型，泛型写法</typeparam>
  /// <returns>object</returns>
  public static T? Get<T>(this ISession session, string key)
  {
    var value = session.GetString(key);
    return value == null ? default : JsonConvert.DeserializeObject<T>(value);
  }
}
